import axios from "axios";
import { BASE_URL } from "@/utils/base_url.js";
import { useTokenStore } from '@/stores'


const http = axios.create({
    baseURL: BASE_URL,
    timeout: 1000 * 30,
    withCredentials: true,
    headers: {
      'Content-Type': 'application/json; charset=utf-8'
    }
})


// request拦截器
http.interceptors.request.use(async(config)=>{
    const tokenStore = useTokenStore()
    // 1.从pinia获取token数据
    if(tokenStore.token){
        config.headers["Authorization"] = tokenStore.token;
    }
    return config;
},e=> Promise.reject(e));

let isRefresh = true;
// response拦截器
http.interceptors.response.use(async(response) => {
    const result = response.data;

    if(response.headers["x-refresh"] && isRefresh){
        const tokenStore = useTokenStore()
        isRefresh = false;
        await tokenStore.refreshToken();
        isRefresh = true;
    }

    if(result.code !== 0){
        ElMessage({
            message: result.msg,
            type: 'error',
            duration: 5 * 1000
        })
        // 401 token失效，或权限改变，必须返回登录页
        if (result.code === 401) { 
            // 清除token
            const tokenStore = useTokenStore()
            await tokenStore.clearToken();
            // 返回登录页
            // router.push({path:"/"})
            location.href = '/login';
        }
    }
    return result
  }, error => {
    return Promise.reject(error)
})

export default http;